package com.example.shop_2302.userInfo

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.Res
import com.example.base.entity.SendCodeEntity
import com.example.base.entity.UploadEntity
import com.example.base.entity.UserEntity
import com.example.base.mvvm.BaseViewModel
import com.example.shop_2302.utils.SingleLiveData
import kotlinx.coroutines.launch
import okhttp3.MultipartBody

class UserViewModel:BaseViewModel() {
    //返回值--用户信息
    val userSuccess = MutableLiveData<Res<UserEntity>>()
    val userFail = MutableLiveData<String>()
    fun user(){
        viewModelScope.launch {
            try {
                userSuccess.value = apiServer.user()
            }catch (e:Exception){
                userFail.value = e.message
            }
        }
    }

    //返回--修改密码
    val updateSuccess = MutableLiveData<Res<Boolean>>()
    val updateFail = MutableLiveData<String>()
    fun update(account:String,captcha:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["account"] = account
                map["captcha"] = captcha
                map["password"] = password
                updateSuccess.value = apiServer.update(mapToBody(map))
            }catch (e:Exception){
                updateFail.value = e.message
            }
        }
    }
    //返回值--发送验证
    val sendSuccess = MutableLiveData<Res<SendCodeEntity>>()
    val sendFail = MutableLiveData<String>()
    fun sendCode(phone:String){
        //在作用域中调用挂起函数   自己添加try-catch ,防止有异常情况时，项目直接崩溃
        viewModelScope.launch {
            try {
                sendSuccess.value = apiServer.sendCode(phone)
            }catch (e:Exception){
                sendFail.value = e.message
            }

        }
    }
    //返回值--上传图片
    val uploadSuccess = SingleLiveData<Res<UploadEntity>>()
    val uploadFail  = SingleLiveData<String>()
    fun upload(model:String,part: MultipartBody.Part,pid:String){
        viewModelScope.launch {
            try {
                uploadSuccess.postValue(apiServer.upload(model,part,pid))
            }catch (e:Exception){
                uploadFail.postValue(e.message.toString())
            }
        }
    }
}